/**
 * 贪吃蛇游戏输入控制模块
 */
class GameInput {
  constructor(game) {
    this.game = game;
    this.setupEventListeners();
  }
  
  setupEventListeners() {
    document.addEventListener('keydown', (e) => this.handleKeyDown(e));
    
    // 移动端触摸控制
    let touchStartX = 0;
    let touchStartY = 0;
    
    document.addEventListener('touchstart', (e) => {
      touchStartX = e.touches[0].clientX;
      touchStartY = e.touches[0].clientY;
    });
    
    document.addEventListener('touchend', (e) => {
      const touchEndX = e.changedTouches[0].clientX;
      const touchEndY = e.changedTouches[0].clientY;
      
      const dx = touchEndX - touchStartX;
      const dy = touchEndY - touchStartY;
      
      // 确定滑动方向
      if (Math.abs(dx) > Math.abs(dy)) {
        // 水平滑动
        if (dx > 0) {
          this.game.changeDirection('right');
        } else {
          this.game.changeDirection('left');
        }
      } else {
        // 垂直滑动
        if (dy > 0) {
          this.game.changeDirection('down');
        } else {
          this.game.changeDirection('up');
        }
      }
      
      // 如果游戏未开始，开始游戏
      if (this.game.getGameState().gameState === 'ready') {
        this.game.startGame();
      }
    });
  }
  
  handleKeyDown(e) {
    const { gameState } = this.game.getGameState();
    
    switch (e.key) {
      case 'ArrowUp':
      case 'w':
      case 'W':
        this.game.changeDirection('up');
        if (gameState === 'ready') this.game.startGame();
        break;
      case 'ArrowDown':
      case 's':
      case 'S':
        this.game.changeDirection('down');
        if (gameState === 'ready') this.game.startGame();
        break;
      case 'ArrowLeft':
      case 'a':
      case 'A':
        this.game.changeDirection('left');
        if (gameState === 'ready') this.game.startGame();
        break;
      case 'ArrowRight':
      case 'd':
      case 'D':
        this.game.changeDirection('right');
        if (gameState === 'ready') this.game.startGame();
        break;
      case ' ':
        if (gameState === 'running' || gameState === 'paused') {
          this.game.togglePause();
        } else if (gameState === 'over') {
          this.game.startGame();
        }
        break;
    }
    
    // 防止页面滚动
    if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' '].includes(e.key)) {
      e.preventDefault();
    }
  }
}